# !/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2022/8/17 10:27
# @Author : xyjiang1216
# @Email : jiangxuyan@nudt.edu.cn
# @File : ex.py
# @Version: OpenTSN_planner_builder 1.0
import random
import sys

from PySide6.QtGui import QIcon, QPainter, QColor
from PySide6.QtWidgets import QMainWindow, QApplication

from UI.ui_lib.parse_xml import get_tsn_node_set
from UI.demo_2.ui_struct_bak import TSNNodeButton
from UI.ui.test_ui import Ui_Form

import qdarkstyle


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        # print(self.hasMouseTracking())
        self.line_item = None
        self.ui = Ui_Form()
        self.ui.setupUi(self)

        self.setWindowIcon(QIcon('../img/win_logo.png'))

        self.tsn_button_set = []

        '''下列代码在点击规划按钮的槽函数内执行'''
        topo_xml = '../tmp/topo_feature.xml'
        # 初始化tsn节点
        tsn_node_set = get_tsn_node_set(topo_xml)
        # 初始化tsn_button
        for tsn_node in tsn_node_set:
            tsn_button = TSNNodeButton(tsn_node, self)
            tsn_button.setPos(random.randint(0, 200),
                              random.randint(0, 200))
            self.tsn_button_set.append(tsn_button)
        # 初始化tsn_button的所有子button
        for tsn_node, tsn_button in zip(tsn_node_set,
                                        self.tsn_button_set):
            children = tsn_node.children
            for child_node in children:
                for child_tsn_button in self.tsn_button_set:
                    if child_tsn_button.tsn_node.node_id == \
                            child_node.node_id:
                        tsn_button.appendChildren(child_tsn_button)

    # 将节点之间的线添加到图中
    def paintEvent(self, event):
        # print(event)
        qp = QPainter(self)
        qp.begin(self)
        self.drawLines(event, qp)
        qp.end()

    def drawLines(self, event, qp):
        # print('yes')
        qp.setPen(QColor(168, 34, 3))
        for tsn_button in self.tsn_button_set:
            # print(id(tsn_button))
            parent_tsn_button = tsn_button
            for child_tsn_button in parent_tsn_button.children:
                # print(parent_tsn_button.pos_x + 17.5)
                qp.drawLine(parent_tsn_button.pos_x + 17.5,
                            parent_tsn_button.pos_y + 17.5,
                            child_tsn_button.pos_x + 17.5,
                            child_tsn_button.pos_y + 17.5)

    # # 鼠标释放事件
    # def mouseReleaseEvent(self, event):
    #     # 鼠标左键释放
    #     if event.button() == QtCore.Qt.LeftButton:
    #         # 进行重新绘制
    #         self.update()


if __name__ == '__main__':
    app = QApplication([])
    window = MainWindow()

    # apply_stylesheet(app, theme='dark_teal.xml')
    # https://github.com/UN-GCPDS/qt-material/blob/master/README.md#usage
    app.setStyleSheet(qdarkstyle.load_stylesheet(qt_api='pyside6'))

    window.show()
    sys.exit(app.exec())
